/* eslint-disable no-plusplus */
/**
 * Created by ivancai on 2019/5/13.
 * 此工具类请放置一些常用操作函数，如字符操作，存取cookie等
 */
import baseUrl from '@/configs/baseUrl';
import axios from 'axios';

export default {
    getCookie(cname) {
        const name = `${cname}=`;
        const ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            const c = ca[i].trim();
            if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
        }
        return '';
    },
    getQueryString(name) {
        const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
        const r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
    setCookie(cname, cvalue, exdays) {
        const d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        const expires = `expires=${d.toGMTString()}`;
        document.cookie = `${cname}=${cvalue}; ${expires}`;
    },
	
	setSession(key, value) {
	  if (typeof value === 'string') {
		    sessionStorage.setItem(key, value);
	  } else {
		    sessionStorage.setItem(key, JSON.stringify(value));
	  }
	},
	
	getSession(key, isObj) {
	  var data = sessionStorage.getItem(key);
	  if (isObj) { // 是否是对象
	    return JSON.parse(data);
	  } else {
	    return data;
	  }
	},
	
	removeSession(key) {
	  sessionStorage.removeItem(key);
	},
    downloadFile(url, params = {}, withToken = true, needBaseUrl = true) {
        const token = this.getCookie('X-Access-Token');
        const headers = withToken ? {
            'X-Access-Token': token
        } : {};
        url = needBaseUrl ? `${baseUrl}${url}` : url;
        return axios({
            url,
            method: 'GET',
            params,
            responseType: 'blob',
            headers
        });
    },
    downloadBlobFile(blob, filename) {
        const objUrl = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        if ('download' in a) {
            document.body.appendChild(a);
            a.style.display = 'none';
            a.href = objUrl;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(objUrl);
            document.body.removeChild(a);
            return;
        }
        // IE
        navigator.msSaveBlob(blob, filename);
    },

    //获取当前年份和月份
    doHandleDate() {
        var myDate = new Date();
        var tYear = myDate.getFullYear();
        var tMonth = myDate.getMonth();
        var m = tMonth + 1;
        if (m.toString().length == 1) {
            m = "0" + m;
        }
        return tYear + '-' + m;
    }
}
